package org.eae.eldf.framework.security.service;

import java.util.List;
import java.util.Set;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import com.google.common.collect.Sets;

import org.eae.eldf.dao.sys.ISysOperatorDao;
import org.eae.eldf.dao.sys.impl.SysOperatorDaoImpl;
import org.eae.eldf.entity.sys.Authorization;
import org.eae.eldf.entity.sys.SysOperator;
import org.eae.eldf.entity.sys.SysPurview;
import org.eae.eldf.framework.spring.SpringSecurityUtils;

public class MyAuthenticationManager implements UserDetailsService {
	
	@Autowired
	private ISysOperatorDao sysOperatorDao;
	
	public void setSysOperatorDao(SysOperatorDaoImpl sysOperatorDao) {
		this.sysOperatorDao = sysOperatorDao;
	}

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		// TODO Auto-generated method stub
		//根据用户名查询操作员
				SysOperator operator = sysOperatorDao.findOperatorByLoginName(username);
				if (operator == null){
					throw new BadCredentialsException(SpringSecurityUtils.LOGIN_ERROR_PWD);
				}else{
					if(operator.getBisfreeze()==1){
						throw new BadCredentialsException(SpringSecurityUtils.LOGIN_ERROR_FREEZE);
					}
				}
				
				
				//得到该用户的所有角色的权限集合
				Set<GrantedAuthority> grantedAuths = obtainGrantedAuthorities(operator);
				
				boolean enabled = true;
				boolean accountNonExpired = true;
				
				boolean credentialsNonExpired = true;
				
				boolean accountNonLocked = true;
				
				//封装到系统UserDetails
//				UserDetails userdetails = new User(
//						operator.getSusername(), operator.getSpassword(), enabled,accountNonExpired, 
//						credentialsNonExpired,accountNonLocked, grantedAuths);
				
				UserDetails userdetails = new Authorization(operator.getSusername(),
						operator.getSpassword().toLowerCase(), enabled, accountNonExpired, credentialsNonExpired,
						accountNonLocked, grantedAuths, operator.getSysOperatorId(),
						operator.getSrealname(), operator.getSoperatorno());
				
				//System.out.println("执行：OperatorDetailsService.class的loadUserByUsername()......");
				
				return userdetails;
	}
	
	/**
	 * 获得用户所有角色的权限集合.
	 * 
	 */
	private Set<GrantedAuthority> obtainGrantedAuthorities(SysOperator operator) {
		Set<GrantedAuthority> authSet = Sets.newHashSet();
		List<SysPurview> list = sysOperatorDao.findUserAuthCodes(operator.getSusername());
		for(SysPurview p : list){
			authSet.add(new GrantedAuthorityImpl(p.getSurlpath()));
			
		}
		return authSet;
	}
	

}
